﻿using System;
using System.Text;
using System.Windows.Forms;

namespace QAToolsAddin.GenericDialogs.Fields {

    public class FieldRadioBT : Field, IField {
        public event EventHandler ValueChanged;
        readonly Panel _control;

        public FieldRadioBT(string name, string[] choices, string info, int selected, bool retore = false)
            : base(name, info, retore) {
            _control = new Panel {
                Height = 22
            };
            for (int i = 0; i < choices.Length; i++) {
                var rb = new RadioButton {
                    AutoSize = true,
                    Checked = i == selected,
                    Text = choices[i]
                };
                rb.CheckedChanged += (sender, e) => {
                    if (ValueChanged != null && ((RadioButton)sender).Checked == true)
                        ValueChanged(sender, e);
                };
                _control.Controls.Add(rb);
            }
            _control.Resize += control_Resize;
        }


        public override Control Control {
            get { return _control; }
        }

        public int Value {
            get {
                int i = -1;
                foreach (RadioButton rb in _control.Controls) {
                    ++i;
                    if (rb.Checked)
                        return i;
                }
                return -1;
            }
            set {
                ((RadioButton)_control.Controls[value]).Checked = true;
            }
        }

        object IField.Value {
            get { return Value; }
            set { Value = (int)value; }
        }

        public override string ToDebugString() {
            var sb = new StringBuilder(base.Label + ":");
            foreach (RadioButton bt in _control.Controls)
                sb.Append(" " + bt.Text + "=" + bt.Checked.ToString());
            return sb.ToString();
        }

        private void control_Resize(object sender, EventArgs e) {
            int len = _control.Controls.Count;
            int top = (_control.Height - _control.Controls[0].Height) / 2 + 1;
            for (int i = 0; i < len; i++) {
                _control.Controls[i].Left = i == 0 ? 0 : _control.Controls[i-1].Left + _control.Controls[i-1].Width;
                _control.Controls[i].Top = top;
            }
        }

    }

}